/**
 * 检查是否是对象
 */
const isObject = (item: any): item is object => {
  return item && typeof item === 'object' && !Array.isArray(item)
}

/**
 * 对象深度合并工具函数
 * 将多个对象深度合并为一个新对象
 * @param objects 需要合并的对象列表
 * @returns 合并后的新对象
 */
export const deepMerge = <T extends object>(...objects: Partial<T>[]): T => {
  const result = {} as T
  objects.forEach((obj) => {
    if (obj) {
      Object.keys(obj).forEach((key) => {
        const value = obj[key as keyof typeof obj]
        const existing = result[key as keyof T]

        // 如果两者都是对象，递归合并
        if (isObject(value) && isObject(existing)) {
          result[key as keyof T] = deepMerge(existing, value) as any
        } else {
          // 简单值直接覆盖
          result[key as keyof T] = value as any
        }
      })
    }
  })
  return result
}

/**
 * 合并组件默认配置和用户提供的配置
 * @param defaultConfig 默认配置
 * @param userConfig 提供的配置
 * @returns 合并后的配置
 */
export const mergeConfig = <T extends object>(defaultConfig: T, userConfig?: Partial<T>): T => {
  return deepMerge(defaultConfig, userConfig || {})
}
